package com.vf.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.vf.activity.domain.DTO.ActivitiesDTO;
import com.vf.activity.mapper.ActivitiesMapper;
import com.vf.common.client.WeChatClient;
import com.vf.common.constant.UserConstants;
import com.vf.common.core.domain.entity.SysUser;
import com.vf.common.exception.ServiceException;
import com.vf.common.utils.SecurityUtils;
import com.vf.system.mapper.SysUserMapper;
import com.vf.system.service.ISysUserService;
import com.vf.user.domain.DTO.*;
import com.vf.user.domain.VO.UserAppletRegisterByPhoneVO;
import com.vf.user.domain.VO.UserAppletRegisterVO;
import com.vf.user.domain.VO.UserVO;
import com.vf.user.mapper.UserTagsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vf.user.mapper.UsersMapper;
import com.vf.user.domain.Users;
import com.vf.user.service.IUsersService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户Service业务层处理
 * 
 * @author LBS
 * @date 2025-06-04
 */
@Service
public class UsersServiceImpl implements IUsersService
{
    private static final Logger log = LoggerFactory.getLogger(UsersServiceImpl.class);
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private UserTagsMapper userTagsMapper;
    @Autowired
    private ActivitiesMapper activitiesMapper;

    @Autowired
    private WeChatClient weChatClient;

    @Autowired
    private SysUserMapper userMapper;






    /**
     * 查询用户
     * 
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public Users selectUsersById(Long id)
    {
        return usersMapper.selectUsersById(id);
    }

    /**
     * 查询用户列表
     * 
     * @param users 用户
     * @return 用户
     */
    @Override
    public List<Users> selectUsersList(Users users)
    {
        return usersMapper.selectUsersList(users);
    }

    /**
     * 新增用户
     * 
     * @param users 用户
     * @return 结果
     */
    @Override
    public int insertUsers(Users users)
    {
        return usersMapper.insertUsers(users);
    }

    /**
     * 修改用户
     * 
     * @param users 用户
     * @return 结果
     */
    @Override
    public int updateUsers(Users users)
    {
        return usersMapper.updateUsers(users);
    }

    /**
     * 批量删除用户
     * 
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUsersByIds(Long[] ids)
    {
        return usersMapper.deleteUsersByIds(ids);
    }

    /**
     * 删除用户信息
     * 
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteUsersById(Long id)
    {
        return usersMapper.deleteUsersById(id);
    }

    @Override
    public UsersDTO getUserById(Long userId) {
        return usersMapper.getUserById(userId);
    }

    @Override
    public UserDTO getUserInfo(Long userId) {
        return usersMapper.getUserInfo(userId);
    }

    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        int i = usersMapper.deleteUserById(userId);
        int j = usersMapper.deleteSysUserById(userId);
        if (i > 0 && j > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public int updateUserAvatar(Long userId, String avatar) {
        return usersMapper.updateUserAvatar(userId,avatar);
    }

    @Override
    @Transactional
    public int updateUserInfo(UserVO userVO) {
        int j = usersMapper.updateUserInfo(userVO);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userVO.getUserId());
        sysUser.setEmail(userVO.getEmail());
        sysUser.setPhonenumber(userVO.getPhone());
        int i = sysUserService.updateUser(sysUser);
        if (i > 0 && j > 0){
            return i;
        }
        return 0;
    }

    @Override
    @Transactional
    public boolean registerUserByEmail(RegisterDTO dto) {
        // 密码加盐
        String encryptPassword = SecurityUtils.encryptPassword(dto.getPassword());
        dto.setPassword(encryptPassword);
        // 设置默认用户名，昵称、头像
        dto.setUserName(dto.getEmail());
        if ("".equals(dto.getNickName()) || dto.getNickName() == null){
            dto.setNickName("用户" + dto.getEmail());
        }else {
            dto.setNickName(dto.getNickName());
        }
        dto.setAvatar(UserConstants.DEFAULT_MAN_AVATAR);
        UserDTO byEmail2 = usersMapper.findByEmail2(dto.getEmail());
        if (byEmail2 != null){
            return false;
        }
        // TODO 初始化一些内容
        int j = usersMapper.insertUser2(dto);
        int i = usersMapper.insertUser(dto);
        if (i > 0 && j > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean registerUserByPhone(RegisterDTO dto) {
        // 密码加盐
        String encryptPassword = SecurityUtils.encryptPassword(dto.getPassword());
        dto.setPassword(encryptPassword);
        // 设置默认用户名，昵称、头像
        dto.setUserName(dto.getPhonenumber());
        if ("".equals(dto.getNickName()) || dto.getNickName() != null){
            dto.setNickName("用户" + dto.getPhonenumber());
        }else {
            dto.setNickName(dto.getNickName());
        }
        dto.setAvatar(UserConstants.DEFAULT_MAN_AVATAR);
        UserDTO byEmail2 = usersMapper.findPhone(dto.getPhonenumber());
        if (byEmail2 != null){
            return false;
        }
        // TODO 初始化一些内容
        int j = usersMapper.insertUser2(dto);
        int i = usersMapper.insertUser(dto);
        if (i > 0 && j > 0){
            return true;
        }
        return false;
    }

    @Override
    public UserVO loginByPass(SysUser user) {
        // 先通过手机号查
        UserDTO phone = usersMapper.findByPhone2(user);
        log.info("数据库中的用户信息：{}", phone);
        if (phone != null) {
            // 说明数据库中存在该用户
            log.info("密码比对结果：{}", SecurityUtils.matchesPassword(user.getPassword(), phone.getPasswordHash()));
            if (SecurityUtils.matchesPassword(user.getPassword(), phone.getPasswordHash())) {
                log.info("密码正确");
                UserVO dto = new UserVO();
                BeanUtil.copyProperties(phone, dto);
                return dto;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public int updateUserProfile(UserUpdateDTO updateDTO) {
        log.info("修改用户信息：{}", updateDTO);
        int i = usersMapper.updateUserProfile(updateDTO);
        if (!"".equals(updateDTO.getName())){
            usersMapper.updateUserByName(updateDTO.getName(), updateDTO.getId());
        }
        List<Long> tags1 = new ArrayList<>();
        if (updateDTO.getTags().size() > 0){
             tags1 = userTagsMapper.getTags(updateDTO.getTags());
            int i1 = userTagsMapper.deleteUserTagsByUserId(updateDTO.getId());
            int j = userTagsMapper.insert(updateDTO.getId(),tags1);
        }
        if (i > 0 ){
            return 1;
        }
        return 0;
    }

    @Override
    public int updateUserInfo2(UsersUpDTO updateDTO) {
        int i = usersMapper.updateUserInfo2(updateDTO);
        usersMapper.updateUserByName2(updateDTO.getNickname(), updateDTO.getPhonenumber(),updateDTO.getAvatar(),updateDTO.getUserId());
        return 0;
    }

    @Override
    public List<ActivitiesDTO> getReceivedInviteCount(Long userId) {
        return activitiesMapper.getReceivedInviteCount(userId);
    }

    @Override
    public List<ActivitiesDTO> getSentInviteCount(Long userId) {
        return activitiesMapper.getSentInviteCount(userId);
    }

    @Override
    @Transactional
    public int respondToInvite(AppDTO appDTO) {
        if ("REJECTED".equals(appDTO.getStatus())){
            return activitiesMapper.respondToInvite(appDTO);
        }
        int i = activitiesMapper.respondToInvite(appDTO);
        int i1 = activitiesMapper.insertActivityParticipants(appDTO.getApplicationId(), appDTO.getApplicantId());
        if (i > 0 && i1 > 0){
            return i;
        }
        return 0;
    }

    @Override
    public int deleteUserAccount(Users1 user) {
        return usersMapper.deleteUserAccount(user.getUserId());
    }

    @Override
    public UsersLoginDTO appletLogin(String code) {
        String openId = weChatClient.getOpenId(code);
        log.debug("用户的openid：{}", openId);
        if (openId == null) {
            throw new ServiceException("微信登录失败");
        }

        SysUser user = usersMapper.selectUserByOpenId(openId);
        log.debug("user: {}", user);
        UsersLoginDTO dto = new UsersLoginDTO();
        if (user != null) {
            BeanUtil.copyProperties(user, dto);
            return dto;
        }
        dto.setOpenid(openId);
        return dto;
    }

    @Override
    public void appletRegister(UserAppletRegisterVO vo) {
        if (usersMapper.selectUserByOpenId(vo.getUuid()) != null) {
            // 已存在，抛异常
            throw new ServiceException("该用户已注册");
        }
        // 不存在，则构造用户信息，保存进数据库
        SysUser user = new SysUser();
        BeanUtil.copyProperties(vo, user);
        user.setOpenid(vo.getUuid());
        user.setUserName("用户" + System.currentTimeMillis());
        user.setAvatar(UserConstants.DEFAULT_MAN_AVATAR);
        insertUser(user);
    }

    @Override
    public void appletRegisterByPhone(UserAppletRegisterByPhoneVO vo) {
// 获取微信用户手机号
        String wxUserPhoneNumber = weChatClient.getWxUserPhoneNumber(vo.getCode());
        // 如果获取失败，抛异常
        if (wxUserPhoneNumber == null) {
            throw new ServiceException("用户未绑定手机号");
        }
        // 获取成功，在数据库中查是否已经注册过
        UserInfoDTO user = usersMapper.selectUserByPhoneNumber(wxUserPhoneNumber);
        // 如果已经注册过，抛异常
        if (user != null) {
            throw new ServiceException("用户已经存在");
        }
        // 没有注册过，vo转bean
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(vo, sysUser);
        sysUser.setPhonenumber(wxUserPhoneNumber);
        sysUser.setUserName(wxUserPhoneNumber);
        sysUser.setAvatar(UserConstants.DEFAULT_MAN_AVATAR);
        // 添加用户
        insertUser(sysUser);
    }

    @Transactional
    public int insertUser(SysUser user) {
        log.info("注册");
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        RegisterDTO dto = new RegisterDTO();
        dto.setUserName(user.getEmail());
        dto.setNickName(user.getNickName());
        dto.setAvatar(user.getAvatar());
        dto.setEmail(user.getEmail());
        dto.setPassword(user.getPassword());
        dto.setPhonenumber(user.getPhonenumber());
        dto.setUserId(user.getUserId());
        registerUserByEmail(dto);
        int i = usersMapper.insertUser(dto);
        return rows;
    }



}
